package com.itstyle.seckill.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class ApiInitializationAspect {

    @Pointcut(value = "@annotation(com.itstyle.seckill.aop.ApiInitialization)")
    public void ApiInitialization() {}

    @Around("ApiInitialization()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        ApiInitialization apiInitialization = method.getAnnotation(ApiInitialization.class);
        RequestInitializable requestInitializeStrategy = apiInitialization.initStrategy().newInstance();
        requestInitializeStrategy.initRequest(request);
        return proceedingJoinPoint.proceed();
    }

}